package tgc.rj.garbage;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.litepal.LitePal;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import tgc.rj.garbage.custom.ToastUtils;
import tgc.rj.garbage.utlis.AisleUtils;
import tgc.rj.garbage.utlis.FilesUtils;
import tgc.rj.garbage.utlis.Queue;
import tgc.rj.garbage.utlis.SerialportScanUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout btn1, btn2,btn3;
    private LinearLayout login;
    private Boolean flag = true;
    private AlertDialog dialog;
    private SerialportScanUtils scanUtils;
    private TextView name, phonegz, phonerx;
    public SharedPreferences sz;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String code = msg.getData().getString("data");
            Queue.push(code);

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LitePal.getDatabase();
        sz = this.getSharedPreferences("jcsz", MODE_PRIVATE);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        login = findViewById(R.id.login);
        login.setOnClickListener(this);

        name = findViewById(R.id.name);
        phonegz = findViewById(R.id.phonegz);
        phonerx = findViewById(R.id.phonerx);

        String names = sz.getString("name", "");
        if (names.equals("") || names == null) {
            name.setText("智能自助垃圾取袋机");
        } else {
            String names1 = "智能自助垃圾取袋机" + "（" + names + "）";
            name.setText(names1);
        }

        String phonegzs = sz.getString("gzphone", "15871975188");
        String phonegzs1 = "扫一扫进入小程序" + "\n" + "取袋遇到问题？" + "\n" + "故障电话：" + phonegzs;
        phonegz.setText(phonegzs1);

        String phonerxs = sz.getString("fwphone", "15871975188");
        String phonerxs1 = "湖北百耀信息系统有限公司" + "\n" + "服务热线：" + phonerxs;
        phonerx.setText(phonerxs1);

        AisleUtils.init();
        scanUtils = new SerialportScanUtils(handler);
        scanUtils.openSrialPort();
        scanUtils.start();
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        Integer num = 0;
        Queue.empty();
        switch (v.getId()) {
            case R.id.btn1:
                num = AisleUtils.getNum(1);
                if (num > 0) {
                    intent = new Intent(this, CanyuActivity.class);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                } else {
                    AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("该种类垃圾袋已没货，无法在进行取货！")
                            .setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                }
                            }).create();
                    alertDialog2.show();
                }
                break;
            case R.id.btn2:
                num = AisleUtils.getNum(2);
                if (num > 0) {
                    intent = new Intent(this, CanyuActivity.class);
                    intent.putExtra("type", 2);
                    startActivity(intent);
                } else {
                    AlertDialog alertDialog2 = new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("该种类垃圾袋已没货，无法在进行取货！")
                            .setIcon(R.mipmap.ic_launcher)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                }
                            }).create();
                    alertDialog2.show();

                }
                break;
            case R.id.btn3:
                String url = sz.getString("url","");
                if(url==null||url.equals("")){
                    intent = new Intent(this,SettingActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.login:
                showNormalDialog();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        flag = true;
                        Queue.empty();
                        while (flag) {
                            final String s = Queue.pop();
                            if (s != null) {
                                sendLogin(s.trim(), dialog);
                            }
                        }
                    }
                }).start();
                break;
        }
    }

    /***
     * 引导员-登录请求
     * 请求地址：weixin/ydysh
     * @param openId 引导员openId
     * @param dialog 弹窗
     */
    private void sendLogin(final String openId, final AlertDialog dialog) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                String urls = sz.getString("url", "https://baiyao.51baiyao.com");
                String urlstr = urls + "/gsm/weixin/ydysh";
                URL url;
                try {
                    url = new URL(urlstr);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    String param = "openId=" + openId;
                    OutputStream outputStream = conn.getOutputStream();
                    DataOutputStream out = new DataOutputStream(outputStream);
                    out.writeBytes(param);
                    out.flush();
                    out.close();
                    InputStream inputStream = conn.getInputStream();
                    final String response = FilesUtils.readInfo(inputStream);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            boolean b = Boolean.parseBoolean(response);
                            if (b) {
                                dialog.dismiss();
                                Intent intent = new Intent(MainActivity.this, PushActivity.class);
                                intent.putExtra("user", openId);
                                startActivity(intent);
                                flag = false;
                            } else {
                                ToastUtils.toastUtils(MainActivity.this, "没有该引导员");
                            }
                        }
                    });
                    if (conn != null) {
                        conn.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        scanUtils.falg = false;
        scanUtils.closeSerialPort();
        super.onDestroy();
    }

    private void showNormalDialog() {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.drawable.logo);
        normalDialog.setTitle("扫码登陆");
        normalDialog.setCancelable(false);
        normalDialog.setMessage("管理员手机码即可登陆");
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        flag = false;
                    }
                });
        // 显示
        dialog = normalDialog.show();
    }
}